package com.example.aichat.controller;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;

import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;


@RestController//返回的JSON 数据
@RequestMapping("/deepseek")
@RequiredArgsConstructor//自动生成包含 final 字段的构造函数
public class DeepSeekClient {

    private final ChatClient chatClient;
    private final Memory memory;
    @CrossOrigin(origins = "http://localhost:8081")
    @RequestMapping(value = "/question", produces = "text/html;charset=utf-8")
    public Flux<String> chat2(@RequestParam String prompt,@RequestParam String userid) {
        // 获取当前对话历史，不存在则初始化
        System.out.println(userid);
        List<Message> messageList = memory.get(userid);
        if (messageList == null) {
            messageList = new ArrayList<>();
        }

        // 存储用户消息到历史
        Message userMessage = new UserMessage(prompt);
        memory.add(userid, userMessage);

        // 使用 AtomicReference 包装 StringBuilder
        AtomicReference<StringBuilder> fullAnswerRef = new AtomicReference<>(new StringBuilder());

        // 调用流式API
        return chatClient.prompt()
                .messages(messageList) // 携带历史上下文
                .user(prompt)
                .stream()
                .content()
                .map(chunk -> {
                    // 5. 实时返回流数据给前端，并拼接片段
                    fullAnswerRef.get().append(chunk); // 累积到StringBuilder
                    return chunk;
                })
                .doOnComplete(() -> {
                    // 6. 流结束时，将完整回答存入历史
                    String fullAnswer = fullAnswerRef.get().toString();
                    Message aiMessage = new AssistantMessage(fullAnswer);
                    memory.add(userid, aiMessage);
                    System.out.println("[DEBUG] 存储完整回答: " + fullAnswer);
                });
    }
}